"""
UI自动化相关Schema模型
"""

from typing import List, Optional, Dict, Any, Union
from datetime import datetime
from pydantic import BaseModel, Field, validator
import json
from ..models.ui_automation import UiAutomationStatus, ExecutionStatus


# UI自动化脚本相关Schema
class UiAutomationScriptBase(BaseModel):
    name: str = Field(..., description="脚本名称")
    description: Optional[str] = Field(None, description="脚本描述")
    requirement_id: Optional[int] = Field(None, description="关联需求ID")
    yaml_content: str = Field(..., description="YAML脚本内容")
    status: UiAutomationStatus = Field(default=UiAutomationStatus.DRAFT, description="脚本状态")
    tags: Optional[str] = Field(None, description="标签，多个标签用逗号分隔")


class UiAutomationScriptCreate(UiAutomationScriptBase):
    pass


class UiAutomationScriptUpdate(BaseModel):
    name: Optional[str] = Field(None, description="脚本名称")
    description: Optional[str] = Field(None, description="脚本描述")
    requirement_id: Optional[int] = Field(None, description="关联需求ID")
    yaml_content: Optional[str] = Field(None, description="YAML脚本内容")
    status: Optional[UiAutomationStatus] = Field(None, description="脚本状态")
    tags: Optional[str] = Field(None, description="标签，多个标签用逗号分隔")


class UiAutomationScript(UiAutomationScriptBase):
    id: int
    created_by: int
    created_at: datetime
    updated_at: datetime

    class Config:
        from_attributes = True


class UiAutomationScriptWithDetails(UiAutomationScript):
    creator_name: Optional[str] = None
    requirement_title: Optional[str] = None
    execution_count: int = 0
    last_execution_status: Optional[ExecutionStatus] = None
    last_execution_time: Optional[datetime] = None


# YAML脚本生成相关Schema
class YamlGenerationRequest(BaseModel):
    requirement_id: int = Field(..., description="需求ID")
    requirement_content: str = Field(..., description="需求内容")
    test_scenarios: List[str] = Field(..., description="测试场景列表")
    additional_requirements: Optional[str] = Field(None, description="额外要求")


class YamlGenerationResponse(BaseModel):
    yaml_content: str = Field(..., description="生成的YAML内容")
    script_name: str = Field(..., description="建议的脚本名称")
    description: str = Field(..., description="脚本描述")


# 执行相关Schema
class UiAutomationExecutionCreate(BaseModel):
    script_id: int = Field(..., description="脚本ID")
    execution_name: Optional[str] = Field(None, description="执行名称")


class UiStepResultDetail(BaseModel):
    id: int
    step_index: int
    step_type: str
    step_content: Optional[str]
    status: ExecutionStatus
    start_time: Optional[datetime]
    end_time: Optional[datetime]
    duration: Optional[int]
    error_message: Optional[str]
    screenshot_url: Optional[str]
    result_data: Optional[Dict[str, Any]]

    class Config:
        from_attributes = True


class UiTaskResultDetail(BaseModel):
    id: int
    task_name: str
    task_index: int
    status: ExecutionStatus
    start_time: Optional[datetime]
    end_time: Optional[datetime]
    duration: Optional[int]
    step_count: int
    success_steps: int
    failed_steps: int
    error_message: Optional[str]
    result_data: Optional[Dict[str, Any]]
    screenshot_urls: Optional[List[str]]
    step_results: List[UiStepResultDetail] = []

    class Config:
        from_attributes = True


class UiAutomationExecution(BaseModel):
    id: int
    script_id: int
    execution_name: Optional[str]
    status: ExecutionStatus
    start_time: Optional[datetime]
    end_time: Optional[datetime]
    duration: Optional[int]
    success_count: int
    failed_count: int
    total_count: int
    error_message: Optional[str]
    result_data: Optional[Dict[str, Any]]
    execution_options: Optional[Dict[str, Any]]
    execution_type: Optional[str] = 'single'
    script_name: Optional[str]
    report_file_name: Optional[str]
    execution_logs: Optional[str]
    result_json_path: Optional[str]
    screenshots_path: Optional[str]
    logs_path: Optional[str]
    executed_by: int
    created_at: datetime

    @validator('result_data', pre=True)
    def parse_result_data(cls, v):
        """解析result_data JSON字符串为字典"""
        if isinstance(v, str) and v.strip():
            try:
                return json.loads(v)
            except (json.JSONDecodeError, TypeError):
                return None
        return v

    @validator('execution_options', pre=True)
    def parse_execution_options(cls, v):
        """解析execution_options JSON字符串为字典"""
        if isinstance(v, str) and v.strip():
            try:
                return json.loads(v)
            except (json.JSONDecodeError, TypeError):
                return None
        return v

    class Config:
        from_attributes = True


class UiAutomationExecutionDetail(UiAutomationExecution):
    script_name: Optional[str] = None
    executor_name: Optional[str] = None
    task_results: List[UiTaskResultDetail] = []


# 批量执行相关Schema
class UiAutomationBatchCreate(BaseModel):
    name: str = Field(..., description="批量执行名称")
    description: Optional[str] = Field(None, description="批量执行描述")
    script_ids: List[int] = Field(..., description="脚本ID列表")


class UiAutomationBatch(BaseModel):
    id: int
    name: str
    description: Optional[str]
    script_ids: List[int]
    total_scripts: int
    completed_scripts: int
    success_scripts: int
    failed_scripts: int
    status: ExecutionStatus
    start_time: Optional[datetime]
    end_time: Optional[datetime]
    duration: Optional[int]
    created_by: int
    created_at: datetime

    class Config:
        from_attributes = True


class UiAutomationBatchDetail(UiAutomationBatch):
    creator_name: Optional[str] = None
    script_names: List[str] = []
    execution_details: List[UiAutomationExecution] = []


# 脚本列表查询参数
class UiAutomationScriptListParams(BaseModel):
    page: int = Field(default=1, ge=1, description="页码")
    size: int = Field(default=20, ge=1, le=100, description="每页大小")
    search: Optional[str] = Field(None, description="搜索关键字")
    requirement_id: Optional[int] = Field(None, description="需求ID过滤")
    status: Optional[UiAutomationStatus] = Field(None, description="状态过滤")
    tags: Optional[str] = Field(None, description="标签过滤")
    created_by: Optional[int] = Field(None, description="创建人过滤")


# 执行列表查询参数
class UiAutomationExecutionListParams(BaseModel):
    page: int = Field(default=1, ge=1, description="页码")
    size: int = Field(default=20, ge=1, le=100, description="每页大小")
    script_id: Optional[int] = Field(None, description="脚本ID过滤")
    status: Optional[ExecutionStatus] = Field(None, description="状态过滤")
    executed_by: Optional[int] = Field(None, description="执行人过滤")


# 通用响应Schema
class UiAutomationListResponse(BaseModel):
    items: List[Any]
    total: int
    page: int
    size: int
    pages: int


class UiAutomationResponse(BaseModel):
    success: bool
    message: str
    data: Optional[Any] = None
